import os
import io
import sys
import json
from openpyxl import load_workbook

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

def initialize_data(directory):
    """初始化数据：扫描 Excel 文件并生成 JSON"""
    if not os.path.isdir(directory):
        print(f"指定目录无效: {directory}")
        sys.exit(1)

    new_data = {}
    error_log = []

    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.xlsx', '.xls')):
                file_path = os.path.abspath(os.path.join(root, file))
                try:
                    wb = load_workbook(file_path, read_only=True)
                    for sheet in wb.sheetnames:
                        new_data.setdefault(sheet, []).append(file_path)
                    wb.close()
                except Exception as e:
                    error_log.append(f"{file_path}: {str(e)}")

    if not new_data:
        print("未找到任何有效的 Excel 文件")
        sys.exit(2)

    # 输出路径：项目目录/Assets/Configs/sheet_data.json
    base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../.."))
    output_path = os.path.join(base_dir, "Assets", "Configs", "sheet_data.json")
    os.makedirs(os.path.dirname(output_path), exist_ok=True)

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(new_data, f, indent=2, ensure_ascii=False)

    print(f"成功生成 JSON 文件，共包含 {len(new_data)} 个 sheet")
    if error_log:
        print("部分文件解析失败（最多显示 5 个）:")
        for line in error_log[:5]:
            print(line)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: python init_excel_data.py <Excel目录>")
        sys.exit(1)

    excel_dir = sys.argv[1]
    initialize_data(excel_dir)
